<template>
  <div class="create-order-container">
    <div class="main-content">
      <!-- 标题 -->
      <div class="page-title">
        <div class="right-info">
          <span>付款信息</span>
          <span class="item-count">共1件商品</span>
        </div>
      </div>

      <!-- 地址选择区域 -->
      <div class="address-section">
        <div class="section-header">
          <div class="title">确认收货地址</div>
          <a-button type="link" class="manage-btn" @click="handleManageAddress">
            管理收货地址
            <template #icon><EditOutlined /></template>
          </a-button>
        </div>
        <div class="address-list" :class="{ collapsed: !showAllAddresses }">
          <a-radio-group v-model:value="selectedAddressId">
            <div class="address-row">
              <div
                v-for="address in displayAddresses"
                :key="address.id"
                class="address-item"
                :class="{ selected: selectedAddressId === address.id }"
              >
                <a-radio :value="address.id">
                  <div class="address-content">
                    <div class="address-main">
                      <div class="location-icon">
                        <EnvironmentOutlined />
                      </div>
                      <div class="address-details">
                        <div class="address-line">
                          {{ formatFullAddress(address) }}
                        </div>
                        <div class="contact-line">
                          <span class="name">{{ address.consignee }}</span>
                          <span class="phone">{{
                            formatPhone(address.phone)
                          }}</span>
                        </div>
                        <div v-if="address.label" class="tag-line">
                          <a-tag class="address-tag">{{ address.label }}</a-tag>
                        </div>
                      </div>
                    </div>
                    <div class="address-actions">
                      <a-button
                        type="link"
                        size="small"
                        @click.stop="handleEditAddress(address)"
                      >
                        编辑
                      </a-button>
                    </div>
                  </div>
                </a-radio>
              </div>
            </div>
          </a-radio-group>
        </div>
        <div
          v-if="addressList.length > 3"
          class="expand-btn"
          @click="toggleAddresses"
        >
          <span>{{ showAllAddresses ? "收起地址" : "显示更多地址" }}</span>
          <DownOutlined :class="{ rotated: showAllAddresses }" />
        </div>
      </div>

      <!-- 订单信息区域 -->
      <div class="order-section">
        <div class="section-header">
          <div class="title">确认订单信息</div>
        </div>

        <!-- 表头 -->
        <div class="order-table-header">
          <div class="col product-col">商品信息</div>
          <div class="col attr-col">商品属性</div>
          <div class="col price-col">单价</div>
          <div class="col quantity-col">数量</div>
        </div>

        <!-- 商品列表 -->
        <div class="product-list">
          <!-- 从购物车来的商品列表 -->
          <template v-if="orderSource === 'cart'">
            <div v-for="item in cartItems" :key="item.id" class="product-item">
              <!-- 商品信息 -->
              <div class="product-col">
                <div class="product-info">
                  <img
                    :src="item.productImage"
                    :alt="item.productName"
                    class="product-image"
                    @error="handleImageError"
                  />
                  <div class="product-details">
                    <div class="product-name">{{ item.productName }}</div>
                  </div>
                </div>
              </div>

              <!-- 商品属性 -->
              <div class="attr-col">
                <div class="product-attrs">
                  <span>尺码：{{ item.size }}</span>
                </div>
              </div>

              <!-- 单价 -->
              <div class="price-col">
                <span class="unit-price">¥{{ item.price?.toFixed(2) }}</span>
              </div>

              <!-- 数量 -->
              <div class="quantity-col">
                <span>{{ item.quantity }}</span>
              </div>
            </div>
          </template>

          <!-- 直接购买的商品 -->
          <template v-else>
            <div class="product-item">
              <!-- 商品信息 -->
              <div class="product-col">
                <div class="product-info">
                  <img
                    :src="product?.imageUrl"
                    :alt="product?.name"
                    class="product-image"
                    @error="handleImageError"
                  />
                  <div class="product-details">
                    <div class="product-name">{{ product?.name }}</div>
                  </div>
                </div>
              </div>

              <!-- 商品属性 -->
              <div class="attr-col">
                <div class="product-attrs">
                  <span>颜色：{{ product?.color }}</span>
                  <span>尺码：{{ selectedSize }}</span>
                </div>
              </div>

              <!-- 单价 -->
              <div class="price-col">
                <span class="unit-price">¥{{ getUnitPrice }}</span>
              </div>

              <!-- 数量 -->
              <div class="quantity-col">
                <a-input-number
                  v-model:value="quantity"
                  :min="1"
                  :max="99"
                  :controls="true"
                  size="small"
                  @change="handleQuantityChange"
                />
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>

    <!-- 提交订单卡片 -->
    <div class="submit-card">
      <div class="card-content">
        <div class="price-detail">
          <div class="price-item">
            <span>商品总价：</span>
            <span class="amount">¥{{ totalPrice }}</span>
          </div>
          <div class="price-item">
            <span>运费：</span>
            <span class="amount">+ ¥0.00</span>
          </div>
          <div class="price-item">
            <span>红包：</span>
            <span class="discount">不可用 ></span>
          </div>
        </div>
        <div class="total-section">
          <div class="address-preview" v-if="selectedAddress">
            <div class="preview-item">
              寄送至：{{ formatFullAddress(selectedAddress) }}
            </div>
            <div class="preview-item">
              收货人：{{ selectedAddress.consignee }}
              {{ formatPhone(selectedAddress.phone) }}
            </div>
          </div>
          <div class="payment-info">
            <span>实付款：</span>
            <span class="total-price">¥{{ totalPrice }}</span>
          </div>
          <a-button
            type="primary"
            class="submit-btn"
            :disabled="!canSubmit"
            :loading="submitting"
            @click="handleSubmitOrder"
          >
            提交订单
          </a-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { message } from "ant-design-vue";
import { listUsingGet } from "@/api/addressBookController";
import {
  createOrderUsingPost,
  createOrderFromCartUsingPost,
} from "@/api/orderController";
import { getProductUsingGet } from "@/api/shangpinjiekou";
import { getCartItemsUsingGet } from "@/api/shoppingCartController";
import type API from "@/api";
import {
  EditOutlined,
  EnvironmentOutlined,
  DownOutlined,
  ShopOutlined,
} from "@ant-design/icons-vue";

const router = useRouter();
const route = useRoute();

// 订单来源（购物车或直接购买）
const orderSource = ref(route.query.from as string);
const cartItems = ref<API.ShoppingCartItemVO[]>([]);

// 商品相关
const product = ref<API.ClothingProduct>();
const selectedSize = ref(route.query.size as string);
const quantity = ref(Number(route.query.quantity) || 1);

// 地址相关
const addressList = ref<API.AddressBook[]>([]);
const selectedAddressId = ref<number>();
const buyerMessage = ref("");
const submitting = ref(false);
const showAllAddresses = ref(false);

// 计算总价
const totalPrice = computed(() => {
  if (orderSource.value === "cart") {
    return cartItems.value
      .reduce(
        (total, item) => total + (item.price ?? 0) * (item.quantity ?? 0),
        0
      )
      .toFixed(2);
  }

  if (!product.value?.price) return "0.00";
  return (product.value.price * quantity.value).toFixed(2);
});

// 获取选中的地址
const selectedAddress = computed(() => {
  return addressList.value.find((addr) => addr.id === selectedAddressId.value);
});

// 是否可以提交订单
const canSubmit = computed(() => {
  if (orderSource.value === "cart") {
    return selectedAddressId.value && cartItems.value.length > 0;
  }
  return selectedAddressId.value && selectedSize.value && quantity.value > 0;
});

// 格式化手机号
const formatPhone = (phone?: string) => {
  if (!phone) return "";
  return `${phone.slice(0, 3)}****${phone.slice(7)}`;
};

// 格式化完整地址
const formatFullAddress = (address: API.AddressBook) => {
  return `${address.provinceName}${address.cityName}${address.districtName}${address.detail}`;
};

// 加载商品信息
const loadProduct = async () => {
  if (orderSource.value === "cart") {
    // 如果是从购物车来的，加载购物车商品信息
    try {
      const res = await getCartItemsUsingGet();
      if (res.data?.code === 0 && res.data.data) {
        // 根据URL中的items参数过滤出选中的商品
        const selectedItemIds = (route.query.items as string).split(",");
        cartItems.value = res.data.data.filter((item) =>
          selectedItemIds.includes(String(item.id))
        );
      }
    } catch (error) {
      message.error("获取购物车商品信息失败");
    }
  } else {
    // 直接购买商品的情况
    try {
      const productId = Number(route.query.productId);
      const res = await getProductUsingGet({ id: productId });
      if (res.data?.code === 0 && res.data.data) {
        product.value = res.data.data;
      }
    } catch (error) {
      message.error("获取商品信息失败");
    }
  }
};

// 加载地址列表
const loadAddressList = async () => {
  try {
    const res = await listUsingGet();
    if (res.data?.code === 0 && res.data.data) {
      addressList.value = res.data.data;
      // 默认选中默认地址
      const defaultAddress = res.data.data.find((addr) => addr.isDefault === 1);
      if (defaultAddress) {
        selectedAddressId.value = Number(defaultAddress.id);
      }
    }
  } catch (error) {
    message.error("获取地址列表失败");
  }
};

// 提交订单
const handleSubmitOrder = async () => {
  if (!canSubmit.value) return;

  try {
    submitting.value = true;
    let res;

    if (orderSource.value === "cart") {
      const orderData = {
        addressId: Number(selectedAddressId.value),
        cartItemIds: cartItems.value.map((item) => String(item.id)),
        buyerMessage: buyerMessage.value,
      };
      res = await createOrderFromCartUsingPost(orderData);
    } else {
      const orderData = {
        addressId: Number(selectedAddressId.value),
        productId: product.value?.id,
        size: selectedSize.value,
        quantity: quantity.value,
        buyerMessage: buyerMessage.value,
      };
      res = await createOrderUsingPost(orderData);
    }

    if (res.data?.code === 0 && res.data.data) {
      message.success("下单成功");
      router.push(`/order/${res.data.data.id}`);
    } else {
      message.error(res.data?.message || "下单失败");
    }
  } catch (error) {
    message.error("创建订单失败");
  } finally {
    submitting.value = false;
  }
};

// 管理收货地址
const handleManageAddress = () => {
  router.push("/address");
};

const handleQuantityChange = (value: number) => {
  quantity.value = value;
};

// 页面加载时获取数据
onMounted(async () => {
  await Promise.all([loadAddressList(), loadProduct()]);
});

// 计算显示的地址列表
const displayAddresses = computed(() => {
  return showAllAddresses.value
    ? addressList.value
    : addressList.value.slice(0, 3);
});

// 切换地址显示
const toggleAddresses = () => {
  showAllAddresses.value = !showAllAddresses.value;
};

// 编辑地址
const handleEditAddress = (address: API.AddressBook) => {
  router.push(`/user/address/edit/${address.id}`);
};

// 修改商品单价显示
const getUnitPrice = computed(() => {
  if (!product.value?.price) return "0.00";
  return product.value.price.toFixed(2);
});

// 处理图片加载错误
const handleImageError = () => {
  // 处理图片加载错误的逻辑
};
</script>

<style scoped>
.create-order-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20px 0 80px;
}

.main-content {
  max-width: 1250px;
  margin: 0 auto;
  padding-right: 300px;
}

.page-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  font-size: 14px;
  color: #333;
}

.right-info {
  color: #999;
}

.item-count {
  margin-left: 20px;
}

.address-section {
  width: 100%;
  background: #fff;
  border-radius: 2px;
  margin-bottom: 10px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.manage-btn {
  color: #1890ff;
  font-size: 14px;
}

.manage-btn .anticon {
  margin-left: 4px;
  font-size: 12px;
}

.address-list {
  padding: 16px 24px;
  transition: all 0.3s;
}

.address-row {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 12px;
}

.address-item {
  flex: 1;
  min-width: 250px;
  max-width: 100%;
  border: 1px solid #e8e8e8;
  border-radius: 2px;
  padding: 12px;
  margin-bottom: 10px;
}

.address-item.selected {
  border-color: #ff4400;
  background: #fff;
}

.address-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.address-main {
  display: flex;
  flex: 1;
  gap: 12px;
}

.location-icon {
  color: #bfbfbf;
  font-size: 16px;
  padding-top: 2px;
}

.address-details {
  flex: 1;
  min-width: 0;
}

.address-line {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  line-height: 1.4;
}

.contact-line {
  color: #666;
  font-size: 13px;
  margin-bottom: 6px;
}

.name {
  margin-right: 12px;
}

.phone {
  color: #999;
}

.tag-line {
  margin-top: 8px;
}

.address-tag {
  background: #fff1f0;
  color: #ff4400;
  border: 1px solid #ffccc7;
  border-radius: 2px;
  font-size: 12px;
  padding: 0 6px;
  line-height: 18px;
}

.address-actions {
  opacity: 0;
  transition: opacity 0.3s;
}

.address-item:hover .address-actions {
  opacity: 1;
}

.expand-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px;
  color: #666;
  cursor: pointer;
  border-top: 1px solid #f0f0f0;
}

.expand-btn:hover {
  color: #1890ff;
}

.expand-btn .anticon {
  margin-left: 4px;
  transition: transform 0.3s;
}

.expand-btn .rotated {
  transform: rotate(180deg);
}

:deep(.ant-radio-wrapper) {
  width: 100%;
}

:deep(.ant-radio) {
  position: absolute;
  right: 16px;
  top: 16px;
}

.order-section {
  width: 100%;
  background: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
}

.section-header {
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.section-header .title {
  font-size: 16px;
  font-weight: 600;
  color: #000;
}

.order-table-header,
.product-item {
  display: grid;
  grid-template-columns: 400px 150px 100px 100px;
  padding: 16px 24px;
  gap: 5px;
  align-items: center;
}

.order-table-header {
  padding: 16px 24px;
  background: #fafafa;
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.product-list {
  padding: 0 24px;
}

.product-item {
  display: grid;
  grid-template-columns: 400px 150px 100px 100px;
  padding: 30px 0;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
}

.product-col {
  text-align: left;
  max-width: 400px;
  padding-right: 10px;
}

.attr-col {
  padding: 0 5px;
  width: 150px;
  text-align: left;
}

.price-col,
.quantity-col {
  width: 100px;
  text-align: center;
  padding: 0;
}

.product-info {
  display: flex;
  gap: 20px;
  width: 100%;
}

.product-image {
  width: 100px;
  height: 100px;
  flex-shrink: 0;
  border: 1px solid #f0f0f0;
}

.product-details {
  flex: 1;
  min-width: 0;
  padding-top: 10px;
}

.product-name {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
  margin: 0 0 10px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-attrs {
  display: flex;
  flex-direction: column;
  gap: 8px;
  color: #999;
  font-size: 12px;
  text-align: left;
  padding-left: 20px;
}

.product-attrs span {
  text-align: left;
  display: block;
  line-height: 1.6;
}

.unit-price {
  color: #ff4400;
  font-size: 14px;
  font-weight: 500;
}

.quantity-col :deep(.ant-input-number) {
  width: 80px;
}

.quantity-col :deep(.ant-input-number-handler-wrap) {
  opacity: 1;
  border-radius: 0;
}

.quantity-col :deep(.ant-input-number-input) {
  text-align: center;
  font-size: 14px;
}

.submit-card {
  position: fixed;
  right: calc((100% - 1250px) / 2);
  top: 180px;
  width: 280px;
  height: 300px;
  background: #fff;
  border-radius: 2px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  border: 1px solid #e8e8e8;
  z-index: 10;
}

.submit-card:hover {
  transform: none;
  box-shadow: none;
}

.card-content {
  position: relative;
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.card-content::before {
  content: "";
  position: absolute;
  top: 0;
  left: 24px;
  right: 24px;
  height: 1px;
  background: linear-gradient(
    90deg,
    transparent 0%,
    #f0f0f0 20%,
    #f0f0f0 80%,
    transparent 100%
  );
}

.price-detail {
  margin-bottom: 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.price-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  font-size: 12px;
  color: #666;
}

.price-item .amount {
  color: #ff4400;
  font-weight: 500;
}

.discount {
  color: #999;
  cursor: pointer;
}

.total-section {
  border-top: 1px solid #f0f0f0;
  padding-top: 15px;
  margin-top: auto;
}

.payment-info {
  margin-bottom: 15px;
}

.total-price {
  color: #ff4400;
  font-size: 20px;
  font-weight: bold;
}

.submit-btn {
  width: 100%;
  height: 40px;
  background: #ff4400;
  border-color: #ff4400;
  font-size: 14px;
  font-weight: 500;
}

.submit-btn:hover {
  background: #f20;
  border-color: #f20;
}

.address-preview {
  background: #f8f8f8;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 20px;
}

.preview-item {
  color: #666;
  font-size: 13px;
  line-height: 1.8;
  display: flex;
  align-items: flex-start;
}

.preview-item:before {
  content: "";
  width: 4px;
  height: 4px;
  background: #999;
  border-radius: 50%;
  margin: 8px 8px 0 0;
}

.order-table-header .attr-col {
  text-align: left;
  padding-left: 30px;
}
</style>
